import { ReportCode } from '@CONSTANTS/BleConstants'
import ReportData from '@MODEL/ReportData'
import { dataType } from '@pier88health/p8h-common'

class ReportDataParser {
  private static findParameters = (tokens: Array<string>) => {
    const paramList: Array<number> = []
    const paramIndex = tokens.slice().findIndex((item) => item.toLowerCase() === 'params:')
    let stringDesc : string = ''
    if (paramIndex >= 0) {
      const list = tokens.slice(paramIndex + 1, tokens.length)
      let indexToString = list.findIndex((item) => dataType.isNumber(item[0]) && Number(item) >= 0)

      list.slice(0, indexToString).forEach((item) => paramList.push(Number(item)))
      if (indexToString < 0) {
        indexToString = list.length
      }
      const stringList = list.slice(indexToString, list.length)
      if (stringList.length > 0) {
        stringDesc = stringList.join(' ')
      }
    } else {
      const stringList = tokens.slice(4, tokens.length)
      if (stringList.length > 0) {
        stringDesc = stringList.join(' ')
      }
    }
    return { paramList, stringDesc }
  }

  private static parseTokens = (tokens: Array<string>): ReportData => {
    const code = (tokens[1] ? parseInt(tokens[1], 16) : ReportCode.NO_VALUE) as ReportCode
    const result = this.findParameters(tokens)

    return new ReportData({
      code,
      parameters: result.paramList,
      stringDescription: result.stringDesc,
    })
  }

  static parse(data?: string | null) {
    const trimmedString = data?.substr(0, data?.lastIndexOf(String.fromCharCode(0))).trim()
    const tokens = trimmedString?.split(' ')
    console.log('ReportDataParser: ReportData = ', trimmedString)

    if (!tokens || tokens.length === 0) {
      return new ReportData()
    }
    const reportData = this.parseTokens(tokens)
    console.log('ReportData after parsing=', reportData)
    return reportData
  }
}

export default ReportDataParser
